<!--  图片预览页面 -->
<!-- 接收上一个页面传递过来的图片链接、 -->
<template>
	<view class="preview">
		<!-- 多个图片 -->
		<swiper v-if="fileType ==='image' && materialUrl.length > 1" :indicator-dots=" true" :autoplay="true"
			:interval="3000" :duration="1000" circular>
			<swiper-item v-for="item in materialUrl" :key="item.materialId">
				<image @click="maskChange" :src="item" mode="aspectFit" webp></image>
			</swiper-item>
		</swiper>
		<!-- 单个图片 -->
		<view v-if="fileType ==='image' && materialUrl.length === 1" class="single-img">
			<image @click="maskChange" :src="materialUrl[0]" mode="aspectFit" webp>
			</image>
		</view>
		<!-- 音频 -->
		<view v-if="fileType ==='audio'">
			<view class="audio">
				<image @click="maskChange" src="https://picsum.photos/200/300" mode="aspectFill" webp>
				</image>
				<view class="overlay"><DHS-Audio :activeIndex="0" :audioData="audioList" showCoverImage
						:autoplay="false" :showAudioListIcon="false" showAudioSpeedIcon @onAudioChange="onAudioChange"
						@onAudioEnd="onAudioEnd" @onPlayProgress="onPlayProgress"></DHS-Audio>
				</view>
			</view>
		</view>
		<!-- 视频播放 -->
		<view v-if="fileType ==='video'" :style="{height:videoHeight + 'px'}">
			<view class="video">
				<image @click="maskChange" :src="materialInfo.thumbnailUrl" mode="aspectFill" webp>
				</image>
				<view class="overlay">
					<video :src="materialUrl[0]" :controls="true" :autoplay="false" :loop="true"
						:show-center-play-btn="false" :show-mute-btn="false" :show-fullscreen-btn="true"
						:enable-progress-gesture="false" :objectFit="fill" :direction="90"
						:title="materialUrl[0].materialTitle" :poster="poster" @fullscreenchange="fullscreenchange"
						@ended="videoEnd" @error="videoError" @timeupdate="videoTimeUpdate"
						@loadedmetadata="videoLoadedmetadata"></video>
				</view>
			</view>
		</view>

		<!-- 下方的遮罩层-->
		<view class="mask" v-show="maskState">
			<view class="goBack" :style="{top:getStatusBarHeight() + 'px' , height:getTitleBraHeight() + 'px'}"
				@click="goBack">
				<uni-icons type="back" color="#fff" size="20" class="icon-back"></uni-icons>
			</view>
			<view class="count" v-if="fileType ==='image'">
				共{{materialUrl.length}}张
			</view>
			<view class="time">
				<uni-dateformat :date="Date.now()" format="hh:mm"></uni-dateformat>
			</view>
			<view class="date">
				<uni-dateformat :date="Date.now()" format="MM/dd"></uni-dateformat>
			</view>
			<view class="footer">
				<view class="box" @click="showInfo">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box" @click="handleCollect">
					<uni-icons v-if="!isCollect" type="star" size="28"></uni-icons>
					<uni-icons v-else type="star-filled" size="28"></uni-icons>

					<view class="text">{{materialInfo.collectionCount ? materialInfo.collectionCount : 0 }}</view>
				</view>
				<view class="box" @click="handleDownload">
					<uni-icons type="download" size="25"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
		<view>
			<!-- 信息弹出层 -->
			<uni-popup ref="infoPopup" type="bottom" :safe-area="false" border-radius="10px 10px 0 0">
				<view class="infoPopup">
					<view class="popHeader">
						<view class="">

						</view>
						<view class="title">素材信息</view>
						<view class="close" @click="closeInfo">
							<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
						</view>
					</view>
					<scroll-view scroll-y>
						<view class="content">
							<view class="row">
								<view class="label">素材ID: </view>
								<text selectable
									class="value">{{materialInfo.materialId?materialInfo.materialId:"无"}}</text>
							</view>
							<view class="row">
								<view class="label">
									分类:
								</view>
								<text selectable
									class="value highlight">{{materialInfo.typeName?materialInfo.typeName:"无"}}</text>
							</view>
							<view class="row">
								<view class="label">
									发布者:
								</view>
								<text selectable
									class="value">{{materialInfo.createBy?materialInfo.createBy:"无"}}</text>
							</view>

							<view class="row" v-if="materialInfo.materialSummary">
								<view class="label">
									摘要:
								</view>
								<text selectable
									class="value">{{materialInfo.materialSummary?materialInfo.materialSummary:"无"}}</text>
							</view>
							<view class="row" v-if="materialInfo.materialTags">
								<view class="label">
									标签:
								</view>
								<view class="value tabs">
									<view class="tab" v-for="(item,index) in materialTags" :key="index">{{item}}
									</view>
								</view>
							</view>
							<view class="copyright">
								声明：本素材来用户投稿，非商业使用，用于免费学习交流，如侵犯了您的权益，您可以拷贝素材ID举报至平台，邮箱2253373466@qq.com，管理将删除侵权素材，维护您的权益。
							</view>
						</view>
						<view class="safe-area-inset-bottom">
						</view>
					</scroll-view>
				</view>
			</uni-popup>

			<uni-popup ref="downloadPopup" type="bottom" :safe-area="false" border-radius="10px 10px 0 0">
				<view class="downloadPopup">
					<view class="popHeader">
						<view class="title">选择下载内容</view>
						<view class="close" @click="closeDownloadPopup">
							<uni-icons type="closeempty" size="20" color="#999"></uni-icons>
						</view>
					</view>
					<scroll-view scroll-y class="download-list">
						<view v-for="(item, index) in materialUrl" :key="index" class="download-item"
							@click="downloadSingle(item)">
							<text>素材 {{ index + 1 }}</text>
							<uni-icons type="download" size="20" color="#666"></uni-icons>
						</view>
						<view class="safe-area-inset-bottom">
						</view>
					</scroll-view>
				</view>
			</uni-popup>

		</view>

	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		onMounted
	} from "vue"
	import {
		onLoad,
		onReady,
		onPageScroll,
		onShow,
		onReachBottom
	} from "@dcloudio/uni-app"

	import {
		getStatusBarHeight,
		getTitleBraHeight,
		getNavbarHeight
	} from '@/utils/system.js'

	import {
		collect,
		cancelCollect,
		collectStatus,
		getMaterial
	} from '@/api/preview.js'

	import {
		useUserInfoStore
	} from "@/stores/modules/user.js"

	onLoad(() => {
		// 获取父页面传递的参数
		materialId.value = JSON.parse(uni.getStorageSync('materialInfo')).materialId
		// 获取素材数据
		getMaterialInfo()
	})

	onReady(() => {
		console.log("materialInfo:", materialInfo.value);
	})


	const userTokenInfo = useUserInfoStore();

	const maskState = ref(true)
	const infoPopup = ref(null)
	// 下载弹出层
	const downloadPopup = ref(null)

	// 总评分
	const totalScore = ref(0)
	// 用户的评分
	const score = ref(0)
	// 素材信息
	const materialInfo = ref('')
	// 素材id
	const materialId = ref('')

	// 收藏状态
	const isCollect = ref(false)


	// 文件类型判断
	const fileType = computed(() => {
		console.log("文件类型:", materialInfo.value);
		let extension = materialInfo.value.materialFormatType ? materialInfo.value.materialFormatType : '';
		console.log("文件类型:", extension);
		if (["jpg", "jpeg", "png", "gif", "webp", "svg"].includes(extension))
			return "image";
		if (["mp3", "wav", "ogg", "aac"].includes(extension)) return "audio";
		if (["mp4", "avi", "mov", "webm", "mkv"].includes(extension)) return "video";
		return "unknown";
	})

	// 素材地址 (数组形式)
	const materialUrl = computed(() => {
		if (fileType == "audio") {
			return JSON.parse(materialInfo.value.materialUrl)[0]
		}

		// materialInfo.value.materialUrl 是json数组字符串
		if (typeof materialInfo.value.materialUrl === "string") {
			console.log("是json数组字符串");
			return JSON.parse(materialInfo.value.materialUrl)
		}

		if (Array.isArray(materialInfo.value.materialUrl)) {
			console.log("是数组");
			return materialInfo.value.materialUrl;
		}

	})

	// 获取素材信息
	const getMaterialInfo = () => {
		getMaterial(materialId.value).then(res => {
			if (res.code == 200) {
				materialInfo.value = res.data
				// 查看素材是否收藏
				checkCollect()
			} else {
				uni.showToast({
					title: res.msg,
					icon: "error"
				})
			}
		})
	}

	// 素材标签
	const materialTags = computed(() => {
		const tags = materialInfo.value.materialTags;
		if (tags) {
			try {
				return JSON.parse(tags);
			} catch (error) {
				console.error("Invalid JSON format:", error);
				return [];
			}
		} else {
			return [];
		}
	})

	// 音频播放器数据
	const audioList = computed(() => {
		return [{
			fileUrl: materialUrl.value,
			title: materialInfo.value.materialTitle,
			coverImage: materialInfo.value.thumbnailUrl,

		}]
	})



	const onAudioChange = (data, index) => {
		console.log("data:", data);
		console.log("index:", index);
	}
	// 整个列表播放结束事件
	const onAudioEnd = () => {

	}

	const onPlayProgress = (currentTime, duration) => {
		console.log("currentTime:", currentTime);
	}


	// 查看收藏状态
	const checkCollect = () => {
		let data = {
			userId: userTokenInfo.userId,
			materialId: materialInfo.value.materialId,
		}

		collectStatus(data).then(res => {
			if (res.code == 200) {
				isCollect.value = res.isCollect
			}
		})
	}


	// 遮罩层状态
	const maskChange = () => {
		maskState.value = !maskState.value
	}
	// 展示素材信息
	const showInfo = () => {
		infoPopup.value.open()
	}

	// 关闭弹窗
	const closeInfo = () => {
		infoPopup.value.close()
	}


	// 确定评分
	const confirmScore = () => {
		// 逻辑处理，修改状态
		totalScore.value = score.value
		socrePopup.value.close()
	}

	// 返回上一页
	const goBack = () => {
		uni.navigateBack()
	}


	// 处理下载按钮点击
	const handleDownload = () => {
		if (materialUrl.value.length > 1) {
			downloadPopup.value.open()
		} else {
			downloadSingle(materialUrl.value[0])
		}
	}
	// 单个文件下载
	const downloadSingle = async (url) => {

		try {
			uni.showLoading({
				title: '下载源文件中...',
				mask: true
			});
			// 获取文件的本地缓存url
			const {
				tempFilePath
			} = await uni.downloadFile({
				url: url,
				timeout: 5000,
			})

			// 根据文件类型处理保存
			switch (fileType.value) {
				// 根据文件类型保存到相册或文件系统
				case 'image':
					await uni.saveImageToPhotosAlbum({
						filePath: tempFilePath,
						success: (res) => {
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							})
						},
						fail: (err) => {
							if (err.errMsg == "saveImageToPhotosAlbum:fail cancel") {
								uni.showToast({
									title: '取消保存',
									icon: 'none'
								})
								return
							}

							uni.showModal({
								title: "提示",
								content: "保存文件需要权限--保存至相册",
								showCancel: true,
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success: (res) => {
												if (res.authSetting[
														'scope.writePhotosAlbum'
													]) {
													uni.showToast({
														title: '获取授权成功',
														icon: 'success'
													})
												} else {
													uni.showToast({
														title: '获取授权失败',
														icon: 'none'
													})
												}
											}
										})
									}
									if (res.cancel) {
										uni.showToast({
											title: '获取授权失败',
											icon: 'none'
										})
									}
								},
								fail: (res) => {
									uni.showToast({
										title: '调用Modal失败',
										icon: 'none'
									})
								}
							})
						},
						complete: () => {
							uni.hideLoading()
						}
					})
					break
				case 'video':
					await uni.saveVideoToPhotosAlbum({
						filePath: tempFilePath,
						success: (res) => {
							uni.showToast({
								title: '保存成功',
								icon: 'success'
							})
						},
						fail: (err) => {
							if (err.errMsg == "saveVideoToPhotosAlbum:fail cancel") {
								uni.showToast({
									title: '取消保存',
									icon: 'none'
								})
								return
							}

							uni.showModal({
								title: "提示",
								content: "保存文件需要权限--保存至相册",
								showCancel: true,
								success: (res) => {
									if (res.confirm) {
										uni.openSetting({
											success: (res) => {
												if (res.authSetting[
														'scope.writePhotosAlbum'
													]) {
													uni.showToast({
														title: '获取授权成功',
														icon: 'success'
													})
												} else {
													uni.showToast({
														title: '获取授权失败',
														icon: 'none'
													})
												}
											}
										})
									}
									if (res.cancel) {
										uni.showToast({
											title: '获取授权失败',
											icon: 'none'
										})
									}
								},
								fail: (res) => {
									uni.showToast({
										title: '调用Modal失败',
										icon: 'none'
									})
								}
							})
						},
						complete: () => {
							uni.hideLoading()
						}
					})
					break
				case 'audio':
					const savedFilePath = await saveMediaFile(tempFilePath, fileType.value)
					console.log('文件保存路径:', savedFilePath)
					// 可以提示用户保存路径
					uni.showToast({
						title: `文件已保存至${savedFilePath}`,
						icon: 'none'
					})
					break
			}
		} catch (error) {
			uni.showToast({
				title: '下载失败: ' + error.errMsg,
				icon: 'none',
				duration: 3000
			})
			console.error('下载失败:', error)
		} finally {
			uni.hideLoading()
			downloadPopup.value.close()
		}
	}

	// 保存媒体文件
	const saveMediaFile = (tempPath) => {
		return new Promise((resolve, reject) => {
			const fileManager = uni.getFileSystemManager()
			const fileExt = materialInfo.value.materialFormatType || 'mp4'
			const fileName = `${Date.now()}_${Math.floor(Math.random()*1000)}.${fileExt}`

			// 微信小程序保存到用户文件目录
			let filePath = ''
			// #ifdef MP-WEIXIN
			//本地路径开头使用file://，跟上手机文件本地目录storage/emulated/0，
			filePath = `${wx.env.USER_DATA_PATH}/${fileName}`
			// #endif
			// 默认选择download文件夹
			// #ifdef APP-PLUS
			// const downloadsDir = plus.io.PUBLIC_DOWNLOADS;
			// filePath = downloadsDir + '/' + fileName;
			// #endif

			// console.log("文件路径：", filePath);
			// console.log('应用的沙盒目录路径:', uni.env.USER_DATA_PATH);
			// 判断文件夹是否存在
			// fileManager.access({
			// 	path: filePath,
			// 	success: () => {
			// 		resolve(filePath)
			// 	},
			// 	fail: () => {
			// 		// 创建文件夹
			// 		fileManager.mkdirSync({
			// 			dirPath: filePath,
			// 			success: () => {
			// 				resolve(filePath)
			// 			},
			// 			fail: (err) => {
			// 				reject(new Error('创建文件夹失败: ' + JSON.stringify(err)))
			// 			}
			// 		})
			// 	}
			// })

			// 保存文件  保存在微信的默认文件夹
			fileManager.saveFile({
				tempFilePath: tempPath,
				filePath: filePath,
				success: (res) => {
					resolve(res.savedFilePath)
				},
				fail: (err) => {
					reject(new Error('保存文件失败: ' + JSON.stringify(err)))
				}
			})
		})
	}

	// 收藏素材
	const handleCollect = () => {
		let data = {
			userId: userTokenInfo.userId,
			materialId: materialInfo.value.materialId,
		}
		// 已收藏
		if (isCollect.value) {

			// 取消收藏
			cancelCollect(data).then((res) => {
				if (res.code === 200) {
					uni.showToast({
						title: '取消收藏',
						icon: 'success'
					})
					isCollect.value = false
					materialInfo.value.collectionCount -= 1
				}
			})


		} else {
			// 未收藏
			collect(data).then((res) => {
				if (res.code === 200) {
					uni.showToast({
						title: '收藏成功',
						icon: 'success'
					})
					isCollect.value = true
					materialInfo.value.collectionCount += 1
				}
			})
		}

	}

	// 关闭下载页
	const closeDownloadPopup = () => {
		downloadPopup.value.close()
	}
</script>

<style lang="scss" scoped>
	.preview {
		width: 100%;
		height: 100vh;
		position: relative;

		swiper {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}
		}

		.single-img {
			width: 100%;
			height: 100%;

			image {
				width: 100%;
				height: 100%;
			}
		}

		// 音频
		.audio {
			width: 100%;
			height: 100vh;
			position: relative;
			align-items: center;
			justify-content: center;

			image {
				width: 100%;
				height: 100%;
				z-index: -1;
			}

			.overlay {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 80%;
				height: 50%;
				background: rgba(0, 0, 0, 0);
				display: flex;
				align-items: center;
				justify-content: center;
			}


		}

		.video {
			width: 100%;
			height: 100vh;
			position: relative;
			align-items: center;
			justify-content: center;

			image {
				width: 100%;
				height: 100%;
				z-index: -1;
			}

			.overlay {
				position: absolute;
				top: 50%;
				left: 50%;
				transform: translate(-50%, -50%);
				width: 80%;
				height: 50%;
				background: rgba(0, 0, 0, 0);
				display: flex;
				align-items: center;
				justify-content: center;
			}
		}



		// 下方遮罩层
		.mask {
			&>view {
				position: absolute;
				left: 0;
				right: 0;
				margin: auto;
				color: #fff;
				width: fit-content;
			}

			.goBack {
				width: 38px;
				height: 38px;
				background: rgba(0, 0, 0, 0.5);
				left: 30rpx;
				margin-left: 0;
				border-radius: 30%;
				top: 0;
				backdrop-filter: blur(10rpx);
				border: 1rpx so1id rgba(255, 255, 255, 0.3);
				display: flex;
				align-items: center;
				justify-content: center;

				.icon-back {
					// 加大按钮的点击范围
					padding: 19rpx 20rpx;
				}
			}

			.count {

				top: 10vh;
				background: rgba(0, 0, 0, 0.3);
				font-size: 28rpx;
				border-radius: 40rpx;
				padding: 8rpx 28rpx;
				backdrop-filter: blur(10rpx);
			}

			.time {
				font-size: 140rpx;
				top: calc(10vh + 80rpx);
				font-weight: 100;
				line-height: 1em;
				text-shadow: 0 4rpx rgba(0, 0, 0, 0.3);
				color: lightgray;
			}

			.date {
				font-size: 34rpx;
				top: calc(10vh + 230rpx);
				text-shadow: 0 2rpx rgba(0, 0, 0, 0.3);
				color: lightgray;
			}

			.footer {
				background: rgba(255, 255, 255, 0.8);
				bottom: 10vh;
				width: 65vw;
				height: 120rpx;
				border-radius: 120rpx;
				color: #000;
				display: flex;
				justify-content: space-around;
				align-items: center;
				box-shadow: 0 2rpx 0 rgba(0, 0, 0, 0.1);
				backdrop-filter: blur(20rpx);

				.box {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					// 增加触碰区域
					padding: 2rpx 12rpx;

					.text {
						font-size: 26rpx;
						color: $text-font-color-2;
					}
				}
			}

		}

		.popHeader {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.title {
				color: $text-font-color-2;
				font-size: 30rpx;
			}

			.close {
				padding: 6rpx;
			}
		}

		.infoPopup {
			background: #fff;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;
			overflow: hidden;


			scroll-view {
				max-height: 50vh;

				.content {
					.row {
						display: flex;
						padding: 16rpx 0;
						font-size: 32rpx;
						line-height: 1.7em;
						gap: 20rpx;

						.label {
							color: $text-font-color-3;
							width: 140rpx;
							text-align: right;
							font-size: 30rpx;
							padding-top: 3rpx;

						}

						.value {
							flex: 1;
							width: 0;

						}

						.highlight {
							color: $brand-theme-color
						}

						.roteBox {
							display: flex;
							align-items: center;

							.score {
								font-size: 26rpx;
								color: $text-font-color-2;
								padding-left: 20rpx;
							}
						}

						.tabs {
							display: flex;
							// 允许内容自动换行
							flex-wrap: wrap;

							.tab {
								border: 1px solid $brand-theme-color;
								color: $brand-theme-color;
								font-size: 22rpx;
								padding: 10rpx 30rpx;
								border-radius: 40rpx;
								line-height: 1em;
								margin: 0 10rpx 10rpx 0;
							}
						}

					}

					.copyright {
						font-size: 28rpx;
						padding: 20rpx;
						background: #F6F6F6;
						color: #666;
						border-radius: 10rpx;
						margin: 20rpx 0;
						line-height: 1.6em;
					}
				}
			}

		}


		.socrePopup {
			background: #fff;
			padding: 30rpx;
			width: 70vw;
			border-radius: 30rpx;

			.content {
				padding: 30rpx 0;
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 20rpx;

				.text {
					color: #FFCA3E;
					padding-left: 10rpx;
					width: 80rpx;
					line-height: 1em;
					text-align: right;
				}
			}

			.footer {
				display: flex;
				padding: 10rpx 0;
				align-items: center;
				justify-content: center;
			}
		}

		.downloadPopup {
			background: #fff;
			padding: 30rpx;
			border-radius: 30rpx 30rpx 0 0;
			max-height: 60vh;

			.download-list {
				padding: 50rpx 0;
				max-height: 50vh;
			}

			.download-item {
				display: flex;
				justify-content: space-between;
				align-items: center;
				padding: 30rpx;
				border-bottom: 1rpx solid #eee;

				&:active {
					background-color: #f5f5f5;
				}
			}
		}

	}
</style>